unit ChatProtocol.Sender;

interface

uses IdUDPServer, SysUtils, Math, CommonLib, Classes;

type
TChatProtocolSender = class
  private
    FIP: string;
    FServer: TIdUDPServer;
    FBoundPort: Integer;
    FUsername: string;
public
  procedure SendMessage(const Message, FontStr: string);
  procedure CallUser(const ToUser: string);
  procedure Rename(const NewName: string);
  procedure DenyRequest(const ToUser: string);
  procedure UpdateStatus(Online: Boolean; ForUser: string = '');

  property IP: string read FIP write FIP;
  property Username: string read FUsername write FUsername;

  procedure Send(const Data: string; Wait: Boolean = True);
  procedure SendFmt(const Data: string; Args: array of const; Wait: Boolean = False);

  constructor Create(AServer: TIdUDPServer; aBoundPort: Integer);
end;

implementation

{ TChatProtocolSender }

procedure TChatProtocolSender.CallUser(const ToUser: string);
begin

end;

constructor TChatProtocolSender.Create(AServer: TIdUDPServer; aBoundPort: Integer);
begin
  FServer := AServer;
  FBoundPort := aBoundPort;
  IP := GetLocalIPAddress;
end;

procedure TChatProtocolSender.DenyRequest(const ToUser: string);
begin
  SendFmt('reqdenied %s/%s', [Username, ToUser]);
end;

procedure TChatProtocolSender.Rename(const NewName: string);
begin
  SendFmt('rename %s/%s', [Username, NewName]);
end;

procedure TChatProtocolSender.Send(const Data: string; Wait: Boolean = True);
begin
  // Nese Wait eshte true
  // atehere pritja do behet te
  // threadi kryesor (Behet true vetem kur programi po mbyllet)
  // perndryshe pritja do behet te threadi qe po dergon mesazhin.

  if Wait then
    Sleep(Random(150));

  TThread.CreateAnonymousThread(procedure begin
    if not Wait then
      Sleep(Random(150));

    FServer.Broadcast(Data, FBoundPort);
  end).Start;
end;

procedure TChatProtocolSender.SendFmt(const Data: string; Args: array of const;
    Wait: Boolean = False);
begin
  Send(Format(Data, Args), Wait);
end;

procedure TChatProtocolSender.SendMessage(const Message, FontStr: string);
begin
  // msg derguesi/ip/fonti/teksti
  SendFmt('msg %s/%s/%s/%s', [Username, IP, FontStr, Message]);
end;

procedure TChatProtocolSender.UpdateStatus(Online: Boolean; ForUser: string = '');
begin
  SendFmt('st %s/%s/%d/%s', [Username, ForUser, Integer(Online), IP], not Online);
end;

end.
